import { createAppSlice } from "@/lib/createAppSlice";
import { FlagRecordParams, AddFlagParams, FlagRecord } from "@/type/flag";
import { PayloadAction } from "@reduxjs/toolkit";

export interface FlagState {
    flags: AddFlagParams[]
}

const initialState: FlagState = {
    flags: []
}

export const flagSlice = createAppSlice({
    name: "flag",
    initialState,
    reducers: (create) => ({
        setFlagData: create.reducer((state, action: PayloadAction<FlagState>) => {
            state.flags = action.payload.flags
        }),
        updateFlagData: create.reducer((state, action: PayloadAction<AddFlagParams>) => {
            state.flags.push(action.payload)

        }),
        setFlagClockRecord: create.reducer((state, action: PayloadAction<FlagRecordParams>) => {
            state.flags.forEach((flag) => {
                if (flag.flag_id == action.payload.flag_id) {
                    return flag.list = action.payload.flagClockRecord
                }
            })
        }),
        updateFlagClockRecord: create.reducer((state, action: PayloadAction<FlagRecord>) => {
            state.flags.forEach((flag) => {
                if (flag.flag_id == action.payload.f_id) {
                    return flag.list?.push(action.payload)
                }
            })
        })
    }),
    selectors: {
        selectFlagDetail: (flag) => flag,
        selectFlagClockRecordDetail: (flag, flag_id: number): AddFlagParams => { return flag.flags.find(flag => flag.flag_id == flag_id) ?? {} }
    }
})

export const { setFlagData, updateFlagData, setFlagClockRecord, updateFlagClockRecord } = flagSlice.actions

export const { selectFlagDetail, selectFlagClockRecordDetail } = flagSlice.selectors
